package com.eigaland.change_machine.business.login

import android.hardware.usb.UsbManager
import android.os.Bundle
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.databinding.Observable
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.eigaland.change_machine.R
import com.eigaland.change_machine.business.movielist.MovieListFragment
import com.eigaland.change_machine.business.setup_account.SetUpAccountFragment
import com.eigaland.change_machine.databinding.FragmentLoginBinding
import com.eigaland.change_machine.displaymodel.IDisplayModel
import com.eigaland.change_machine.util.ProgressDialogManager
import com.eigland.eigaland_lib.base.BaseLazyFragment
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.coroutines.Deferred
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator
import me.yokeyword.fragmentation.anim.DefaultVerticalAnimator
import me.yokeyword.fragmentation.anim.FragmentAnimator
import movie6.posprintercept2.extensions.textWatcher
import java.io.BufferedInputStream
import java.io.ByteArrayInputStream
import java.io.FileInputStream
import kotlin.math.abs

public class LoginFragment : BaseLazyFragment<LoginFragmentVM, FragmentLoginBinding>() {
    override fun initVM() {


        ed_input_device_code.textWatcher {
            this.onTextChanged { charSequence, i1, i2, i3 ->
                vm?.clickableStatus?.postValue(charSequence?.isNotEmpty())
            }
        }

        vm?.loginStatus?.observe(this, Observer {
            if(it.loginStatus == IDisplayModel.ERROR_STATUS) {
                Toast.makeText(requireContext(),it.errorMsg,Toast.LENGTH_LONG).show()
            } else {
                var fragment = SetUpAccountFragment()
                var bundle = Bundle()
                bundle.putString("oneTimePwd",it.deviceSecret)
                fragment.arguments = bundle
                supportDelegate.replaceFragment(fragment,false)
            }
        })

        vm?.loadingProgressStatus?.observe(this, Observer {

            if(it) {
                ProgressDialogManager.showDialog(requireContext())
            } else {
                ProgressDialogManager.dismissDialog(requireContext())
            }
        })

    }

    override fun onCreateFragmentAnimator(): FragmentAnimator {
        return DefaultHorizontalAnimator()
    }

    override fun setUpViewData(view: View) {


        binding =  DataBindingUtil.bind<FragmentLoginBinding>(view)
        vm = LoginFragmentVM()

        binding?.let{
            it.loginVM = vm
            it.lifecycleOwner = this
        }



    }

    override fun setLayoutId() = R.layout.fragment_login

}